package com.tywj.buscustomerapp.presenter;

import com.tywj.buscustomerapp.model.MapModel;
import com.tywj.buscustomerapp.model.bean.StationBean;
import com.tywj.buscustomerapp.presenter.contract.MapContract;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class MapPresenter implements MapContract.MapPresenter {

    private MapContract.MapView view;
    private MapContract.MapModel model;

    public MapPresenter(MapContract.MapView view) {
        this.view = view;
        model = new MapModel();
    }

    @Override
    public void onDestroy() {
        view = null;
        System.gc();
    }

    @Override
    public void startLoadStations(final String stationId) {
        Observable.create(new ObservableOnSubscribe<List<StationBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<StationBean>> e){
                List<StationBean> list = model.loadData(stationId);
                if (list!=null && list.size()>0){
                    e.onNext(list);
                }else{
                    e.onError(null);
                }
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<StationBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        view.showLoading();
                    }

                    @Override
                    public void onNext(List<StationBean> s) {
                        if (view!=null && s!=null) {
                            view.loadedData(s);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (view!=null) {
                            view.closeLoading();
                            view.showMsg("线路加载失败");
                        }

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
